/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vista.compras;

import java.util.Iterator;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import modelo.DetalleOrdenDeCompra;
import modelo.DetalleRecepcionOrdenDeCompra;
import modelo.Herramienta;
import modelo.HerramientaDeEmpresa;
import modelo.ItemComprable;
import modelo.OrdenDeCompra;
import modelo.RecepcionOrdenDeCompra;
import modelo.Recurso;
import modelo.RecursoEspecifico;
import util.HibernateUtil;
import util.SwingPanel;
import util.Tupla;
import vista.interfaces.ICallBackGen;

/**
 *
 * @author Emmanuel
 */
public class ABMHerramientaDeEmpresa extends javax.swing.JInternalFrame implements ICallBackGen {

    private HerramientaDeEmpresa herramientaDeEmpresa;
    private int idOrdenDeCompra = -1;
    private int idRecursoEsp = -1;
    /**
     * Creates new form ABMHerramientaDeEmpresa
     */
    public ABMHerramientaDeEmpresa() {
        herramientaDeEmpresa = null;
        initComponents();
        this.habilitarVentana();
        
    }

    public ABMHerramientaDeEmpresa(int idHerramientaDeEmpresa) {
        try {
            HibernateUtil.beginTransaction();
            this.herramientaDeEmpresa = (HerramientaDeEmpresa)HibernateUtil.getSession().get(HerramientaDeEmpresa.class, idHerramientaDeEmpresa);
            HibernateUtil.commitTransaction();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this,"No pudo cargarse la herramienta de Empresa.", "Error al cargar", JOptionPane.ERROR_MESSAGE);
            HibernateUtil.rollbackTransaction();
        }
        initComponents();
        this.habilitarVentana();
    }

    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txtNroSerie = new javax.swing.JTextField();
        cmbEstado = new javax.swing.JComboBox();
        jPanel3 = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        txtNroOrdenDeCompra = new javax.swing.JTextField();
        txtFechaOrdenDeCompra = new javax.swing.JTextField();
        btnAsociarOrdenDeCompra = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        cmbTipoHerramienta = new javax.swing.JComboBox();
        jLabel8 = new javax.swing.JLabel();
        cmbHerramienta = new javax.swing.JComboBox();
        btnCerrar = new javax.swing.JButton();
        btnGuardarHerramienta = new javax.swing.JButton();

        setTitle("ABM Herramienta de Empresa");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos de la Herramienta"));

        jLabel2.setText("Número de Serie:");

        jLabel3.setText("Estado:");

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Orden de Compra Asociada"));

        jLabel4.setText("Nro. Orden:");

        jLabel5.setText("Fecha:");

        txtNroOrdenDeCompra.setEditable(false);
        txtNroOrdenDeCompra.setEnabled(false);

        txtFechaOrdenDeCompra.setEditable(false);
        txtFechaOrdenDeCompra.setEnabled(false);

        btnAsociarOrdenDeCompra.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/iconos/var/16x16/Shopping cart.png"))); // NOI18N
        btnAsociarOrdenDeCompra.setToolTipText("Asociar Herramienta Comprada");
        btnAsociarOrdenDeCompra.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAsociarOrdenDeCompraActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(txtNroOrdenDeCompra, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtFechaOrdenDeCompra, javax.swing.GroupLayout.DEFAULT_SIZE, 111, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnAsociarOrdenDeCompra, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
            .addComponent(btnAsociarOrdenDeCompra)
            .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel4)
                .addComponent(txtNroOrdenDeCompra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel5)
                .addComponent(txtFechaOrdenDeCompra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        jLabel7.setText("Tipo de Herramienta:");

        cmbTipoHerramienta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbTipoHerramientaActionPerformed(evt);
            }
        });

        jLabel8.setText("Herramienta:");

        cmbHerramienta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbHerramientaActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cmbEstado, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel7)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cmbTipoHerramienta, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtNroSerie))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel8)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cmbHerramienta, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(cmbHerramienta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(cmbTipoHerramienta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtNroSerie, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(cmbEstado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        btnCerrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/iconos/var/16x16/block.png"))); // NOI18N
        btnCerrar.setText("Cerrar");
        btnCerrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCerrarActionPerformed(evt);
            }
        });

        btnGuardarHerramienta.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/iconos/var/16x16/save_upload.png"))); // NOI18N
        btnGuardarHerramienta.setText("Guardar");
        btnGuardarHerramienta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarHerramientaActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnGuardarHerramienta)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnCerrar)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCerrar)
                    .addComponent(btnGuardarHerramienta))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnGuardarHerramientaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarHerramientaActionPerformed
        this.guardarCambios();
    }//GEN-LAST:event_btnGuardarHerramientaActionPerformed

    private void cmbHerramientaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbHerramientaActionPerformed
        DefaultComboBoxModel dcbm = (DefaultComboBoxModel) cmbHerramienta.getModel();
        Tupla tupla = (Tupla) dcbm.getSelectedItem();
        if(tupla != null){
            this.llenarComboTipoHerramienta(tupla.getId());
        }
    }//GEN-LAST:event_cmbHerramientaActionPerformed

    private void btnCerrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCerrarActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCerrarActionPerformed

    private void btnAsociarOrdenDeCompraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAsociarOrdenDeCompraActionPerformed
        pantallaConsultarOrdenDeCompraConHerramientas consulta = new pantallaConsultarOrdenDeCompraConHerramientas();
        consulta.setSeleccionarEnabled(this, "ABM Herramienta de Empresa");
        SwingPanel.getInstance().addWindow(consulta);
        consulta.show();
    }//GEN-LAST:event_btnAsociarOrdenDeCompraActionPerformed

    private void cmbTipoHerramientaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbTipoHerramientaActionPerformed
        Tupla tupla = (Tupla) cmbTipoHerramienta.getSelectedItem();
        if(tupla != null)
            this.idRecursoEsp = tupla.getId();
    }//GEN-LAST:event_cmbTipoHerramientaActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAsociarOrdenDeCompra;
    private javax.swing.JButton btnCerrar;
    private javax.swing.JButton btnGuardarHerramienta;
    private javax.swing.JComboBox cmbEstado;
    private javax.swing.JComboBox cmbHerramienta;
    private javax.swing.JComboBox cmbTipoHerramienta;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JTextField txtFechaOrdenDeCompra;
    private javax.swing.JTextField txtNroOrdenDeCompra;
    private javax.swing.JTextField txtNroSerie;
    // End of variables declaration//GEN-END:variables

    private void habilitarVentana() {
        llenarComboHerramientas();
        llenarComboEstadoHerramienta();
        if(this.herramientaDeEmpresa != null)
        {
            this.llenarCamposHerramientaEditada();
        }
    }
    
    private void llenarComboHerramientas() 
    {   
        try 
        {
            HibernateUtil.beginTransaction();
            DefaultComboBoxModel dcbm = (DefaultComboBoxModel) cmbHerramienta.getModel();
            dcbm.removeAllElements();
            Iterator<Herramienta> iter = HibernateUtil.getSession().createQuery("from Herramienta h order by h.id").iterate();
            while (iter.hasNext())
            {
                Herramienta h = iter.next(); 
                Tupla tp = new Tupla(h.getId(),h.getNombre());
                dcbm.addElement(tp);
            }    
            HibernateUtil.commitTransaction();
        } 
        catch (Exception ex) 
        {
            HibernateUtil.rollbackTransaction();
            JOptionPane.showInternalMessageDialog(this,"Error!","Se produjo un error al cargar las Herramientas: "+ ex.getMessage(),JOptionPane.ERROR_MESSAGE);
        }
    }
    
    private void llenarComboTipoHerramienta(int idHerramienta)
    {
        try 
        {
            HibernateUtil.beginTransaction();
            DefaultComboBoxModel dcbm = (DefaultComboBoxModel) cmbTipoHerramienta.getModel();
            dcbm.removeAllElements();
            Herramienta herramienta = (Herramienta) HibernateUtil.getSession().createQuery("from Herramienta h where h.id=:idHerramienta").setParameter("idHerramienta", idHerramienta).uniqueResult();
            Iterator<RecursoEspecifico> iter = (Iterator<RecursoEspecifico>) herramienta.getRecursosEspecificos().iterator();
            while (iter.hasNext())
            {
                RecursoEspecifico re = iter.next(); 
                Tupla tp = new Tupla(re.getId(),re.getNombre());
                dcbm.addElement(tp);
            }    
            HibernateUtil.commitTransaction();
        } 
        catch (Exception ex) 
        {
            HibernateUtil.rollbackTransaction();
            JOptionPane.showInternalMessageDialog(this,"Error!","Se produjo un error al cargar los tipos de Herramienta: "+ex.getMessage(),JOptionPane.ERROR_MESSAGE);
        }
    }
    
    private void llenarComboEstadoHerramienta()
    {
        DefaultComboBoxModel dcbm = (DefaultComboBoxModel) cmbEstado.getModel();
        Iterator<String> itEstados = HerramientaDeEmpresa.getEstados().iterator();
        while(itEstados.hasNext())
        {
            String estado = itEstados.next();
            dcbm.addElement(estado);
        }
    }

    private void guardarCambios() {
        try {
            HibernateUtil.beginTransaction();
            if(herramientaDeEmpresa == null)
            {
                herramientaDeEmpresa = new HerramientaDeEmpresa();
            }
            herramientaDeEmpresa.setEstado((String)this.cmbEstado.getSelectedItem());
            herramientaDeEmpresa.setNroSerie(this.txtNroSerie.getText());
            Tupla tupla = (Tupla)cmbTipoHerramienta.getSelectedItem();
//            RecursoEspecifico recursoEspecifico = (RecursoEspecifico)HibernateUtil.getSession().get(RecursoEspecifico.class, tupla.getId());
//            herramientaDeEmpresa.setRecursoEsp(recursoEspecifico);
            OrdenDeCompra ordenDeCompra = (OrdenDeCompra)HibernateUtil.getSession().get(OrdenDeCompra.class, this.idOrdenDeCompra);
            herramientaDeEmpresa.setOrdenDeCompra(ordenDeCompra);
            RecursoEspecifico recursoEspecifico = (RecursoEspecifico)HibernateUtil.getSession().get(RecursoEspecifico.class, this.idRecursoEsp);
            herramientaDeEmpresa.setRecursoEsp(recursoEspecifico);
            HibernateUtil.getSession().saveOrUpdate(herramientaDeEmpresa);
            HibernateUtil.commitTransaction();
            JOptionPane.showMessageDialog(this,"Se guardó correctamente la Herramienta de Empresa (Nro Serie: "+this.herramientaDeEmpresa.getNroSerie() +").", "Herramienta de Empresa", JOptionPane.INFORMATION_MESSAGE);
            this.dispose();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this,"No pudo guardarse la herramienta de Empresa: "+ e.getMessage(), "Error al guardar", JOptionPane.ERROR_MESSAGE);
            HibernateUtil.rollbackTransaction();
        }
    }

    private void llenarCamposHerramientaEditada() {
        try {
            HibernateUtil.beginTransaction();
            Recurso recurso = (Recurso) HibernateUtil.getSession().createQuery("FROM Recurso AS r WHERE :re in elements(r.recursos)").setParameter("re", this.herramientaDeEmpresa.getRecursoEsp()).uniqueResult();
            this.seleccionarEnCombo(this.cmbHerramienta,recurso.getId());
            this.seleccionarEnCombo(this.cmbTipoHerramienta,this.herramientaDeEmpresa.getRecursoEsp().getId());
            this.txtNroSerie.setText(this.herramientaDeEmpresa.getNroSerie());
            this.seleccionarEnComboEstado(this.cmbEstado,this.herramientaDeEmpresa.getEstado());
            this.txtNroOrdenDeCompra.setText(String.valueOf(this.herramientaDeEmpresa.getOrdenDeCompra().getId()));
            this.txtFechaOrdenDeCompra.setText(this.herramientaDeEmpresa.getOrdenDeCompra().getFechaDeGeneracionFormateada());            
            HibernateUtil.commitTransaction();
        } catch (Exception e) {
            HibernateUtil.rollbackTransaction();
        }

    }

    private void seleccionarEnCombo(JComboBox cb, int id) {
        DefaultComboBoxModel dcbm = (DefaultComboBoxModel)cb.getModel();
        for(int i = 0 ; i < dcbm.getSize() ; i++)
        {
            Tupla tupla = (Tupla) dcbm.getElementAt(i);
            if(tupla.getId() == id)
            {
                cb.setSelectedIndex(i);
                break;
            }
        }
    }
    
    private void seleccionarEnComboEstado(JComboBox cb, String estado) {
        DefaultComboBoxModel dcbm = (DefaultComboBoxModel)cb.getModel();
        for(int i = 0 ; i < dcbm.getSize() ; i++)
        {
            String e = (String) dcbm.getElementAt(i);
            if(e.equals(estado))
            {
                cb.setSelectedIndex(i);
                break;
            }
        }
    }

    @Override
    public void actualizar(int id, String flag, Class tipo) {
        OrdenDeCompra orden;
        try {
            orden = (OrdenDeCompra) HibernateUtil.getSession().get(tipo, id);
            this.idOrdenDeCompra = id;
            this.seleccionarHerramientaDeOrdenDeCompra(orden);
            this.txtNroOrdenDeCompra.setText(String.valueOf(orden.getId()));
            this.txtFechaOrdenDeCompra.setText(orden.getFechaDeGeneracionFormateada());
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this,"No pudo cargarse la Orden de Compra: "+ex.getMessage(), "Error al cargar", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    private void seleccionarHerramientaDeOrdenDeCompra(OrdenDeCompra ordenDeCompra) {
        Iterator<RecepcionOrdenDeCompra> itRecepciones = ordenDeCompra.getRecepciones().iterator();
        while(itRecepciones.hasNext())
        {
            RecepcionOrdenDeCompra recepcion = itRecepciones.next();
            Iterator<DetalleRecepcionOrdenDeCompra> itDetalleRecepciones = recepcion.getRecepcionesParciales().iterator();
            while(itDetalleRecepciones.hasNext())
            {
                DetalleRecepcionOrdenDeCompra detalleRecepcion = itDetalleRecepciones.next();
                DetalleOrdenDeCompra detalle = detalleRecepcion.getDetalleOrdenDeCompra();
                ItemComprable itemComprable = detalle.getItem();
                if(itemComprable!=null && itemComprable.getItem()!=null && itemComprable.getItem() instanceof RecursoEspecifico)
                {
                    RecursoEspecifico recursoEsp = (RecursoEspecifico) itemComprable.getItem();
                    if(!this.yaEstaAsociadaAUnaHerramientaDeEmpresa(recursoEsp))
                    {
                        this.idRecursoEsp = recursoEsp.getId();
                    }
                }
            }
        }
    }  

    private boolean yaEstaAsociadaAUnaHerramientaDeEmpresa(RecursoEspecifico recursoEsp) {
        try {
            HibernateUtil.beginTransaction();
            Iterator<HerramientaDeEmpresa>  itHerramientaDeEmpresa = (Iterator<HerramientaDeEmpresa>)HibernateUtil.getSession().createQuery("FROM HerramientaDeEmpresa").iterate();
            while(itHerramientaDeEmpresa.hasNext())
            {
                HerramientaDeEmpresa herramientaDeEmpresaAux = itHerramientaDeEmpresa.next();
                if(recursoEsp.getId() == herramientaDeEmpresaAux.getRecursoEsp().getId())
                {
                    return true;
                }
            }
            HibernateUtil.commitTransaction();
            return false;
        } catch (Exception e) {
            HibernateUtil.rollbackTransaction();
            return false;
        }
    }
}
